package com.xinqi.modules.course.clazz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xinqi.common.core.constant.CacheConstants;
import com.xinqi.common.core.utils.StringUtils;
import com.xinqi.common.base.utils.RandomUtils;
import com.xinqi.common.mybatis.data.service.impl.BaseServiceImpl;
import com.xinqi.modules.course.clazz.domain.ClassCourseCodeEntity;
import com.xinqi.modules.course.clazz.mapper.ClassCourseCodeMapper;
import com.xinqi.modules.course.clazz.service.ClassCourseCodeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service("classCourseCodeService")
@RequiredArgsConstructor
@Log4j2
public class ClassCourseCodeServiceImpl extends BaseServiceImpl<ClassCourseCodeMapper, ClassCourseCodeEntity> implements ClassCourseCodeService {

    @Resource
    private ClassCourseCodeMapper classCourseCodeMapper;
    @Resource
    private RedisTemplate redisTemplate;

    private ExecutorService threadPool = Executors.newCachedThreadPool();

    @Override
    public void generateNumber(Integer count) {
        threadPool.submit(new Runnable() {
            @Override
            public void run() {
                generateCode(count);
            }
        });

    }

    private void generateCode(Integer count) {
        ClassCourseCodeEntity courseCodeEntity;
        for (int i = 0; i < count; i++) {
            String code = RandomUtils.randomStrUp(6);
            courseCodeEntity = new ClassCourseCodeEntity();
            courseCodeEntity.setCode(code);
            try {
                if (classCourseCodeMapper.insert(courseCodeEntity) > 0) {
                    redisTemplate.opsForList().rightPush(CacheConstants.CLASS_CODE, code);
                    log.info("生成课程码{}", code);
                }
            } catch (Exception e) {
                continue;
            }
        }
    }

    @Override
    public String getClassCode() {
        if (!redisTemplate.hasKey(CacheConstants.CLASS_CODE)) {
            //容错
            generateCode(5);
        }
        String code = (String) redisTemplate.opsForList().leftPop(CacheConstants.CLASS_CODE);
        if(StringUtils.isEmpty(code)) {
            //容错
            generateCode(5);
            code = (String) redisTemplate.opsForList().leftPop(CacheConstants.CLASS_CODE);
        }
        classCourseCodeMapper.delete(new LambdaQueryWrapper<ClassCourseCodeEntity>()
            .eq(ClassCourseCodeEntity::getCode, code));
        return code;
    }
}
